<template>
  <div>
    <el-card class="box-card">
      <el-breadcrumb separator="/" style="margin-bottom: 20px">
        <!-- <el-breadcrumb-item>会议管理 </el-breadcrumb-item> -->
        <el-breadcrumb-item :to="{ path: '/welcome/car' }"
        >工作证办理
        </el-breadcrumb-item
        >
      </el-breadcrumb>
      <template>
        <el-row :gutter="20">
          <el-col :span="2"> 姓名:</el-col>
          <el-col :span="3" class="demo-input-suffix">
            <el-input
              placeholder="姓名"
              clearable
              style="display: inline"
              v-model="sysUser.usrName"
            >
              <!-- <i slot="prefix" class="el-input__icon el-icon-search"></i> -->
            </el-input>
          </el-col>
          <el-col :span="2"> 部门:</el-col>
          <el-col :span="3">
            <!-- 申请人: -->
            <!-- <el-input
                placeholder="部门"
                clearable
                prop="buildingAddress"
                v-model="building.buildingAddress"
              >
                // <i slot="prefix" class="el-input__icon el-icon-search"></i>
              </el-input> -->
            <el-select
              v-model="matters.value"
              @change="towerChange"
              placeholder="请选择"
            >
              <el-option
                v-for="item in matters.list"
                :key="item.id"
                :label="item.departmentName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="2"> 职务:</el-col>
          <el-col :span="3">
            <!-- 联系人: -->
            <el-input
              placeholder="职务"
              clearable
              prop="post"
              v-model="sysUser.post"
            >
              <!-- <i slot="prefix" class="el-input__icon el-icon-search"></i> -->
            </el-input>
          </el-col>
          <el-col :span="2"> 发起时间</el-col>
          <el-col :span="4">
            <!-- <el-input
              placeholder=" "
              clearable
              type="datetime"
              prop="creationTime"
              style="display: inline-flex"
              v-model="sysUser.creationTime"
            > -->
            <!-- <i slot="prefix" class="el-input__icon el-icon-search"></i> -->
            <!-- </el-input> -->
            <el-date-picker
              v-model="sysUser.creationTime"
              type="datetimerange"
              align="right"
              start-placeholder="发起时间"
              end-placeholder="结束日期"
              :default-time="['12:00:00', '08:00:00']"
            >
            </el-date-picker>
            <!-- ~
            <el-input
          format="yyyy-MM-dd HH:mm:ss"
              placeholder="building "
              clearable
              type="datetime"
              prop="creationTime2"
              style="display: inline-flex"
              v-model="sysUser.creationTime2"
            > -->
            <!-- <i slot="prefix" class="el-input__icon el-icon-search"></i> -->
            <!-- </el-input> -->
          </el-col>
          <el-col :span="7">
            <el-button
              type="primary"
              icon="el-icon-search"
              style="display: inline"
              @click="search"
            >搜索
            </el-button
            >
          </el-col>
          <el-col :span="3">
            <el-button type="primary" @click="showAddDialog"
            ><i class="el-icon-plus"></i>添加
            </el-button
            >
          </el-col>
          <el-col :span="3">
            <el-button
              type="primary"
              icon="el-icon-search"
              style="display: inline"
              @click="exportData"
              >导出</el-button
            > 
          </el-col>
        </el-row>
      </template>
      <el-dialog
        title="工作证办理:  "
        :close-on-click-modal="false"
        :visible.sync="addDialogVisible"
        :show-close="true"
      >
        <el-form :model="sysUser" ref="sysUser" :rules="rules">
          <el-form-item
            label="姓名"
            prop="usrName"
            :label-width="formLabelWidth"
          >
            <el-input v-model="sysUser.usrName"></el-input>
          </el-form-item>
          <el-form-item
            label="部门"
            prop="depName"
            :label-width="formLabelWidth"
          >
            <el-select
              v-model="matters1.value"
              @change="towerChange"
              placeholder="请选择"
            >
              <el-option
                v-for="item in matters1.list"
                :key="item.id"
                :label="item.departmentName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="联系手机"
            prop="phone"
            :label-width="formLabelWidth"
          >

            <el-input v-model="sysUser.phone"></el-input>
          </el-form-item>
          <el-form-item
            label="职务"
            prop="post"
            :label-width="formLabelWidth"
          >

            <el-input v-model="sysUser.post"></el-input>
          </el-form-item>
          <el-form-item
            label="上次证件照"
            prop="price"
            :label-width="formLabelWidth"
          >
            <!-- <el-upload
              class="upload"
              ref="upload"
              action=""
              :auto-upload="false"
              :file-list="fileList"
              :http-request="uploadFile"
              :with-credentials='true'
              :on-change="handleChange"
              http-equiv="Access-Control-Allow-Origin"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              multiple="multiple"
            >
          //:file-list="fileList"
            //  show-file-list=true
             //  with-credentials="true"
          //  :headers="Access-Control-Allow-Origin"
              <el-button
                slot="trigger"
                size="small"
                type="primary"
                @click="delFile"
                >点击上传</el-button
              >
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload> -->

            <el-upload
              action="#"
              list-type="picture-card"
              :file-list="fileList"
              class="upload"
              ref="upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-change="handleChange"
              :auto-upload="false"
            >
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{ file }">
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                  alt=""
                />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleDownload(file)"
                  >
                    <i class="el-icon-download"></i>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt=""/>
            </el-dialog>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="onSubmit('sysUser')"
          >保存
          </el-button
          >
        </div>
      </el-dialog>

      <!-- <el-dialog
        title="楼宇维修:  "
        :close-on-click-modal="false"
        :visible.sync="addDialogVisible"
        :show-close="true"
      >
        <div>
          <h4>请填写您需要维修的相关内容</h4>
        </div>

        <el-form :model="building" ref="building" :rules="rules">
          <el-form-item
            label="维修事项"
            prop="buildingMattersId"
            :label-width="formLabelWidth"
          >
            <el-select
              v-model="matters.value"
              @change="towerChange"
              placeholder="请选择"
            >
              <el-option
                v-for="item in matters.list"
                :key="item.mattersId"
                :label="item.mattersName"
                :value="item.mattersId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="故障地点"
            prop="buildingAddress"
            :label-width="formLabelWidth"
          >
            <el-input v-model="building.buildingAddress"></el-input>
          </el-form-item>

          <el-form-item
            label="联系人"
            prop="buildingContactsName"
            :label-width="formLabelWidth"
          >
            <el-input v-model="building.buildingContactsName"></el-input>
          </el-form-item>

          <el-form-item
            label="联系手机"
            prop="buildingPhone"
            :label-width="formLabelWidth"
          >
            <el-input v-model="building.buildingPhone"></el-input>
          </el-form-item>

          <el-form-item
            label="故障描述"
            prop="buildingDistribution"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="building.buildingDistribution"
              type="textarea"
              :rows="5"
              resize="none"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addUser('building')">保存</el-button
          >crud
        </div>
      </el-dialog> -->

      <!-- <el-dialog
          title="车辆预定详情"
          :close-on-click-modal="false"
          :visible.sync="editDialogVisible"
          :show-close="true"
        >
          <el-form :model="car" ref="car" :rules="rules">
            <el-form-item
              label="部门名称"
              prop="car.id"
              :label-width="formLabelWidth"
            >
              <el-input v-model="car.id"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="updateUser('user')">保存</el-button>
          </div>
        </el-dialog> -->
      <el-table border :data="tableData" style="width: 100%; margin-top: 20px">
        <el-table-column prop="usrName" label="姓名"></el-table-column>
        <el-table-column label="证件照">
          <!-- <img src=/> -->
          <template scope="scope">
            　　　<!--　<img v-for="item in scope.row.img"
                                 :src="item" width="100" height="100" :preview-src-list="scope.row.img"
                                 style="margin-left:10px;" class="head_pic"/>-->
            <div class="demo-image__preview">
              <el-image style="width: 100px; height: 100px; margin-left:10px;"
                        :src="scope.row.siteNum"

              ></el-image>
            </div>
            　　
          </template>
        </el-table-column>
        <el-table-column prop="depName" label="部门"></el-table-column>
        <el-table-column prop="post" label="职务"></el-table-column>
        <el-table-column prop="usrnameName" label="申请人"></el-table-column>
        <el-table-column prop="depName" label="归属部门"></el-table-column>
        <el-table-column prop="creationTime" label="发起时间"></el-table-column>
        <el-table-column prop="SysUsrName" label="处理人"></el-table-column>

        <el-table-column
          prop="SysUsrNameData"
          label="处理时间"
        ></el-table-column>
        <el-table-column prop="staticName" label="状态"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="info"
              plain
              size="small"
              style="margin-bottom: 20px"
              @click="deletes(scope.row)"
            >取消
            </el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <template>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="params.pageIndex"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="params.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="params.total"
        >
        </el-pagination>
      </template>
    </el-card>
  </div>
</template>
<script>
  import axios from 'axios'

  export default {
    data () {
      return {
        tableData: [],
        params: {
          pageSize: 5, // 每页显示5条记录
          pageIndex: 1, // 当前第几页
          total: 0, // 共几条记录去分页
        },
        dialogImageUrl: '',
        dialogVisible: false,
        disabled: false,
        fileList: [],
        // 不支持多选
        multiple: false,
        formData: '',
        did: 0,

        sysUser: {
          depName: '', //部门名称
          staticName: '', //状态名称
          usrnameName: '', //申请人名称
          SysUsrName: '', //处理人名称
          usrId: 0, //id
          usrName: '', //姓名
          usrPassword: '', //密码
          depId: 0, //部门id
          phone: '', //联系电话
          post: '', //职务
          creationId: 0, //创建者
          creationTime: '', //创建时间
          staticId: 0, //状态id
          usrnameId: 0, //申请人
          SysUsrNameData: '', //处理时间
          creationTime2: '', //创建时间2
          certificateId: 0, //工作证照id

          site: '', //保存地址
          siteName: '', //保存后文件的名称
          sitesuffix: '', //保存后的文件后缀
          siteOriginal: '', //原生名称
          siteNum: '',//保存全路径
        },
        matters: {
          list: [],
          // mattersId:0,
          // mattersName:"",
          value: '',
        },
        matters1: {
          list: [],
          // mattersId:0,
          // mattersName:"",
          value: '',
        },

        addDialogVisible: false,
        editDialogVisible: false,
        formLabelWidth: '120px',
        rules: {
          phone: [
            {
              required: true,
              message: '请输入手机号',
              trigger: 'blur'
            },
            {
              validator: function (rule, value, callback) {
                if (
                  /^(13[0-9]|14[0-9]|15[0-9]|16[6]|18[0-9]|19[6,9]|17[0-9])\d{8}$/i.test(
                    value
                  ) == false
                ) {
                  callback(new Error('请输入手机号'))
                } else {
                  //校验通过
                  callback()
                }
              },
              trigger: 'blur',
            },
          ],
        },
      }
    },
    computed: {
      // 这里定义上传文件时携带的参数，即表单数据
      upData: function () {
        return {
          body: JSON.stringify(this.sysUser.creationId),
        }
      },
    },
    // mounted:在模板渲染成html后调用，通常是初始化页面完成后，再对html的dom节点进行一些需要的操作
    mounted () {
      this.search()
      this.ss()
    },
    methods: {
         // 导出数据
         exportData() {
      // 1.定义表头对应关系
      const headers = {
        'Id': 'usrId',
        '部门名称': 'depName',
        '状态名称': 'staticName',
        '申请人名称': 'usrnameName',
        '处理人名称': 'SysUsrName',
        '姓名': 'usrName',
        '密码': 'usrPassword',
        '部门id': 'depId',
        '联系电话': 'phone',
        '职务': 'post',
        '状态id': 'staticId',
        '申请人': 'usrnameId',
        '处理时间': 'SysUsrNameData',
        '工作证照id': 'certificateId',
        '保存地址': 'site',
        '保存全路径': 'siteNum',
    
      }
      // 懒加载
      import('@/excel/Export2Excel').then(async excel => {
        // excel是引入文件（也就是@/ventor/Export2Excel）的导出对象
        // 获取所有的数据
        const  rows  =this.tableData;
        // console.log(rows);
    
        const data = this.formatJson(headers, rows) // 返回的data就是我们转化后的数据
        excel.export_json_to_excel({
          // 要求转出的表头是中文
          header: Object.keys(headers), // 表头 必填
          data, // //具体数据 必填
          filename: '车辆预定excel', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
        // 拿到的数据是这种
        //  [{ username: 'xxx', mobile: 'xxx', ... }, { username: 'xxx', mobile: 'xxx', ... }]
        // 要转化的是如下这种
        // header: ['姓名', '手机号', '入职日期', ...]
        // data: [['张三', '138xxxxxxxx', '1992-08-04', ...], ['李四', '135xxxxxxxx', '1992-08-04', ...]]
      })
    },
    formatJson(headers, rows) {
      return rows.map(item => {
        // console.log(item)
        return Object.keys(headers).map(k => {
          if (headers[k] === 'timeOfEntry' || headers[k] === 'correctionTime') {
            return formatDate(item[headers[k]]) // 返回格式化之前的时间
          } else if (headers[k] === 'formOfEmployment') {
            return EmployeeEnum.hireType[item.formOfEmployment] ? EmployeeEnum.hireType[item.formOfEmployment] : '未知'
          }
          return item[headers[k]]
        })
      })
    },
      handleSizeChange (val) {
        console.log(`每页 ${val} 条`)
        this.params.pageSize = val
        this.search()
      },
      handleCurrentChange (val) {
        console.log(`当前页: ${val}`)
        this.params.pageIndex = val
        this.search()
      },

      handleRemove (file) {
        this.fileList=[];
        console.log('s')
        //删除
        this.$message.error('删除成功!')
        console.log(file)
      },
      handlePictureCardPreview (file) {
        //显示
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      handleDownload (file) {
        //下载
        console.log('s2')
        console.log(file)
      },

      //点击上传文件触发的额外事件,清空fileList
      delFile () {
        this.fileList = []
      },
      handleChange (file, fileList) {
        this.fileList = fileList
        // console.log(this.fileList, "sb");
      },
      //自定义上传文件
      uploadFile (file) {
        this.formData.append('file', file.file)

        // console.log(file.file, "sb2");
      },
      // //删除文件
      // handleRemove(file, fileList) {
      //   this.fileList = [];
      //   file = [];
      //   console.log(file, fileList);
      // 点击文件
      handlePreview (file) {
        console.log(file)
      },
      //保存按钮
      async onSubmit (sysUser) {
        this.$refs[sysUser].validate(async (valid) => {
          if (valid) {
            let formData = new FormData()
            console.log(this.fileList)
            formData.append('file', this.fileList[0].raw) //拿到存在fileList的文件存放到formData中
            //下面数据是我自己设置的数据,可自行添加数据到formData(使用键值对方式存储)
            formData.append('title', this.title)
            formData.append('usrName', this.sysUser.usrName)
            formData.append('depId', this.matters1.value)
            formData.append('post', this.sysUser.post)
            formData.append('phone', this.sysUser.phone)

            const url = '/vueboot/sysUser/add'
            //     axios.post(url, formData).then((res) => {
            //   console.log(res);
            // });
            console.log('sss')
            const { data: res } = await this.$ajax.post(url, formData, {
              // params: {
              //   usrName: this.sysUser.usrName,
              //   depId: this.matters1.value,
              //   post: this.sysUser.post,
              //   phone: this.sysUser.phone,
              // },
              headers: {
                token: localStorage.getItem('token'),
                'Content-Type': 'multipart/form-data',
              },
            })
            console.log(res)
            if (res.data > 0) {
              this.$notify({
                title: '成功',
                message: '提交成功',
                type: 'success',
                duration: 1000,
              })
              this.addDialogVisible = false
              sysUser = {
                depName: '', //部门名称
                staticName: '', //状态名称
                usrnameName: '', //申请人名称
                SysUsrName: '', //处理人名称
                usrId: 0, //id
                usrName: '', //姓名
                usrPassword: '', //密码
                depId: 0, //部门id
                phone: '', //联系电话
                post: '', //职务
                creationId: 0, //创建者
                creationTime: '', //创建时间
                staticId: 0, //状态id
                usrnameId: 0, //申请人
                SysUsrNameData: '', //处理时间
                creationTime2: '', //创建时间2
              }
            }
          }
        })
      },
      async search () {
        console.log(this.sysUser.creationTime[0])
        const url = '/vueboot/sysUser/page'
        const { data: res } = await this.$ajax.get(url, {
          params: {
            pageIndex: this.params.pageIndex,
            limit: this.params.pageSize,
            usrName: this.sysUser.usrName,
            post: this.sysUser.post,
            // this.sysUser.creationTime[0],
            creationTime: this.sysUser.creationTime[0],
            // moment(this.sysUser.creationTime[0]).format(
            //   "yyyy-MM-dd HH:mm:ss"
            // ),
            creationTime1: this.sysUser.creationTime[1],
            depId: this.matters.value,
          },
          headers: {
            token: localStorage.getItem('token'),
          },
        })
        console.log(res)
        this.tableData = res.data.records
        this.params.total = res.data.total
      },
      async ss () {
        const url = '/vueboot/department/list'
        const { data: res } = await this.$ajax.get(url, {
          headers: {
            token: localStorage.getItem('token'),
          },
        })
        console.log(res)
        this.matters.list = res.data
        this.matters1.list = res.data
      },
      towerChange (e) {
        //获取的值和id
        console.log(e)
        this.sysUser.id = e
      },

      showAddDialog () {
        this.addDialogVisible = true
      },
      // showAddDialogs() {
      //   this.addDialogVisibles = true;
      // },
      // addUser(building) {
      //   this.$refs[building].validate(async (valid) => {
      //     if (valid) {
      //       const url = "/vueboot/building/add";
      //       const { data: res } = await this.$ajax.post(
      //         url,
      //         this.building,

      //         {
      //           // data:car,
      //           headers: {
      //             token: localStorage.getItem("token"),
      //           },
      //         }
      //       );
      //       console.log(res);
      //       if (res.data > 0) {
      //         this.$message({
      //           message: "添加成功",
      //           type: "success",
      //         });
      //         this.addDialogVisible = false;
      //         this.search();
      //         this.building = {
      //           // 故障地址
      //           buildingAddress: "",
      //           // 故障描述
      //           buildingDistribution: "",
      //           // 归属部门id
      //           buildingDepartment: 0,
      //           // 联系人id
      //           buildingContactsid: 0,
      //           // 归属部门名称
      //           buildingDepartmentName: "",
      //           // 联系人名称
      //           buildingContactsName: "",
      //           //维修事项Id
      //           buildingMattersId: 0,
      //           // 联系人电话
      //           buildingPhone: "",
      //           // 发起时间
      //           buildingStartdata: "",
      //           // 处理状态Id
      //           buildingStatic: 0,
      //           // 处理状态Name
      //           buildingStaticName: "",
      //           //维修事项名称
      //           buildingMattersName: "",
      //           buildingId: 0,
      //         };
      //       } else {
      //         this.$message.error(res.msg);
      //         //  this.$message.error("添加失败");
      //       }
      //     }
      //   });
      // },
      // 根据id删除
      async deletes (row) {
        console.log(row)
        const url = '/vueboot/sysUser/deleteById'
        const { data: res } = await this.$ajax.get(url, {
          params: {
            usrId: row.usrId,
          },
          headers: {
            token: localStorage.getItem('token'),
          },
        })
        if (res.code > 0) {
          this.$message({
            message: '取消成功！',
            type: 'success',
          })
          this.search()
        } else {
          this.$message.error(res.msg)
        }
      },
      //   // 根据id查看用户
      //   async selectById(row) {
      //     console.log(row);
      //     const url = "/vueboot/car/selectById";
      //     const { data: res } = await this.$ajax.get(url, {
      //       params: {
      //         id: this.id,
      //       },
      //       headers: {
      //         token: localStorage.getItem("token"),
      //       },
      //     });
      //     if (res > 0) {
      //       this.$message({
      //         message: "修改成功",
      //         type: "success",
      //       });
      //       this.editDialogVisible = false;
      //       this.search();
      //     } else {
      //       this.$message.error("修改失败");
      //     }

      //     // this.user.usrName = row.usrName
      //     // this.did = row.usrId
      //     this.editDialogVisible = true;
      //   },
    },
  }
</script>
<style>
  .breadcrumb {
    height: 30px;
  }
</style>
